<template>
  <div>
    <section class="shop_container">
      <header class="shop-header">
        <head-top go-back="true"></head-top>
        <div class="header_cover_img_con">
          <img
            :src="imgBaseUrl + shopDetailData.image_path"
            class="header_cover_img"
          />
        </div>
        <section class="description-header">
          <!-- TODO:路径实现 -->
          <router-link class="description-top" to="/shop/shopDetail">
            <section class="description_left">
              <img :src="imgBaseUrl + shopDetailData.image_path" />
            </section>
            <section class="description_right">
              <h4 class="description-name ellipsis">
                {{ shopDetailData.name }}
              </h4>
              <p class="description_text">
                商家配送／{{
                  shopDetailData.order_lead_time || 20
                }}分钟送达／配送费¥{{ shopDetailData.float_delivery_fee }}
              </p>
              <p class="description_promotion ellipsis">
                公告：{{ promotionInfo }}
              </p>
            </section>
            <icon-svg icon-class="iconarrow-left"></icon-svg>
          </router-link>
          <section
            class="detail-header-bottom"
            v-if="shopDetailData.activities && shopDetailData.activities.length"
            @click="changeShowActivities"
          >
            <p class="ellipsis">
              <span
                class="tip-icon"
                :style="{
                  backgroundColor:
                    '#' + shopDetailData.activities[0].icon_color,
                  borderColor: '#' + shopDetailData.activities[0].icon_color,
                }"
                >{{ shopDetailData.activities[0].icon_name }}</span
              ><span class="tip-text"
                >{{ shopDetailData.activities[0].description }}（APP专享）</span
              >
            </p>
            <p>
              <span class="tip-text"
                >{{ shopDetailData.activities.length }}个活动
                <icon-svg icon-class="iconarrow-left"></icon-svg>
              </span>
            </p>
          </section>
        </section>
      </header>
      <transition name="fade">
        <div class="activities" v-if="showActivities">
          <h4 class="activities-name">{{ shopDetailData.name }}</h4>
          <section class="activities-info">
            <h5 class="info-title">优惠信息</h5>
            <section class="info-content">
              <p
                v-for="(item, index) in shopDetailData.activities"
                :key="index"
                class="info-content-p"
              >
                <span
                  :style="{
                    backgroundColor: '#' + item.icon_color,
                    borderColor: '#' + item.icon_color,
                  }"
                  class="info-content-span"
                  >{{ item.icon_name }}</span
                >{{ item.description }}
              </p>
            </section>
          </section>
          <section class="shop-info">
            <h5 class="info-title">商家公告</h5>
            <section class="info-content">
              <p class="info-content-p">{{ shopDetailData.promotion_info }}</p>
            </section>
          </section>
          <icon-svg
            icon-class="iconquxiao1"
            @click.native="changeShowActivities"
          ></icon-svg>
        </div>
      </transition>
      <section class="change-show-type">
        <div>
          <span
            :class="{ activate_type: changeShowType == 'food' }"
            @click="changeShowType = 'food'"
          >
            商品
          </span>
        </div>
        <div>
          <span
            :class="{ activate_type: changeShowType == 'rating' }"
            @click="changeShowType = 'rating'"
          >
            评价
          </span>
        </div>
      </section>
      <div
        class="menuScrollWrapper"
        :style="'height:' + wrapperHeight + 'rem'"
        v-show="changeShowType == 'food'"
      >
        <vue-better-scroll class="food-left" ref="scroll1">
          <ul>
            <li
              v-for="(item, index) in menuList"
              :key="item.id"
              :class="{ actIdx: index == idx }"
              @click="menuClick(index)"
            >
              {{ item.name }}
              <span class="category_num" v-show="categoryNum[index] !== 0">{{
                categoryNum[index]
              }}</span>
            </li>
          </ul>
        </vue-better-scroll>
        <vue-better-scroll
          ref="scroll2"
          class="food-right"
          :probeType="probeType"
          :listenScroll="true"
          @scroll.passive="scrollListener"
        >
          <ul>
            <li v-for="item in menuList" :key="item.id">
              <section class="menu-name">
                {{ item.name
                }}<span class="name-des">{{ item.description }}</span>
              </section>
              <section
                class="menu-food"
                v-for="foodItem in item.foods"
                :key="foodItem.item_id"
              >
                <img
                  :src="imgBaseUrl + foodItem.image_path"
                  alt=""
                  class="menu-food-left"
                />
                <div class="menu-food-mid">
                  <span class="menu-food-name ellipsis">{{
                    foodItem.name
                  }}</span>
                  <span class="menu-food-tips"
                    >月售{{ foodItem.month_sales }}份 好评率{{
                      foodItem.satisfy_rate
                    }}%
                  </span>
                  <span class="menu-food-price"
                    ><span class="yuan">￥</span
                    >{{ foodItem.specfoods[0].price }}
                    <span v-if="foodItem.specfoods.length > 1">起</span>
                  </span>
                </div>
                <div class="menu-food-right">
                  <buy-cart
                    :foods="foodItem"
                    :shopId="shopId"
                    :inCart="inCart"
                    @showReduceTip="showReduceTip"
                    @showChooseList="showChooseList"
                  ></buy-cart>
                </div>
              </section>
            </li>
          </ul>
        </vue-better-scroll>
      </div>
    </section>
    <shop-cart
      :totalPrice="totalPrice"
      :deliveryFee="deliveryFee"
      :minimumOrderAmount="minimumOrderAmount"
      :totalNum="totalNum"
    ></shop-cart>
    <transition name="fade">
      <delete-tip v-if="showDeleteTip"></delete-tip>
    </transition>
    <section>
      <transition name="fade">
        <div class="specs_cover" v-if="showSpecs" @click="showChooseList"></div>
      </transition>
      <transition name="fade">
        <specs-list
          v-if="showSpecs"
          :choosedFoods="choosedFoods"
          :specsIndex="specsIndex"
          :shopId="shopId"
          @showChooseList="showChooseList"
          @changeSpecsInd="changeSpecsInd"
        ></specs-list>
      </transition>
    </section>
    <div class="cart-card-wrap">
      <cart-card :cartFoodList="cartFoodList" :shopId="shopId"></cart-card>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import headTop from "@/components/header/head";
import shopCart from "@/components/common/ShopCart";
import buyCart from "@/components/common/BuyCart";
import specsList from "@/components/common/SpecsList";
import deleteTip from "./children/DeleteTip";
import cartCard from "./children/CartCard";
import { imgBaseUrl } from "@/config/env";
import { calcSize } from "@/components/common/mixin";
import { debounce } from "lodash";
import {
  msiteAddress,
  shopDetails,
  foodMenu,
  getRatingList,
  ratingScores,
  ratingTags,
} from "@/network/getData";
export default {
  name: "",
  data() {
    return {
      geohash: "", //goehash地址信息
      shopId: null, //店铺id
      shopDetailData: {}, //店铺详情数据
      menuList: [], //店铺菜单列表
      ratingList: [], //店铺评论列表
      ratingOffset: 20, //请求评论偏移量
      ratingScoresData: [], //评价分数
      ratingTagsList: [], //评价tags列表
      imgBaseUrl, //图片BaseUrl
      showActivities: false, //是否显示活动卡片
      changeShowType: "food", //激活商品或者评价
      wrapperHeight: 0, //scroll wrapper高度
      menuNameHeight: [0], //menuName dom离父元素顶部高度的列表
      scrollY: 0, //记录滑动位置
      idx: 0, //侧边栏idx
      probeType: 3, //better-scroll监听scroll的一个属性
      categoryNum: [], //商品类型右上角已加入购物车的数量
      totalPrice: 0, //总共价格
      cartFoodList: [], //购物车商品列表
      showDeleteTip: false, //多规格商品减少显示tip
      choosedFoods: null, //保存当前待选择的多规格商品
      specsIndex: 0, //保存多规格商品中选择规格的index
      showSpecs: false, //显示多规格商品选择dom
      inCart: false,
    };
  },
  mixins: [calcSize],
  computed: {
    ...mapState(["latitude", "longitude", "cartList"]),
    promotionInfo: function () {
      return (
        this.shopDetailData.promotion_info ||
        "欢迎光临，用餐高峰期请提前下单，谢谢。"
      );
    },
    currentIndex: function () {
      let idx = this.menuNameHeight.findIndex((height, index) => {
        return (
          this.scrollY <= this.menuNameHeight[index] &&
          this.scrollY > this.menuNameHeight[index + 1]
        );
      });
      return idx;
    },
    shopCart: function () {
      return { ...this.cartList[this.shopId] };
    },
    // 商家配送费
    deliveryFee: function () {
      return this.shopDetailData.float_delivery_fee;
    },
    // 商家起送费
    minimumOrderAmount() {
      return this.shopDetailData.float_minimum_order_amount;
    },
    // 总商品数量
    totalNum() {
      if (this.categoryNum.length) {
        return this.categoryNum.reduce((total, cValue) => total + cValue);
      } else {
        return 0;
      }
    },
  },
  components: { headTop, shopCart, buyCart, specsList, deleteTip, cartCard },
  created() {
    this.geohash = this.$route.query.geohash;
    this.shopId = this.$route.query.id;
    this.INIT_BUYCART();
  },
  mounted() {
    this.initData();
    let head = document.querySelector(".shop-header");
    let changeShowType = document.querySelector(".change-show-type");
    this.wrapperHeight = this.calcSize([head, changeShowType]);
  },
  updated() {
    // TODO:todo
    let menuNameList = document.querySelectorAll("ul li .menu-name");
    if (
      menuNameList.length > 0 &&
      this.menuNameHeight.length < menuNameList.length
    ) {
      for (let i = 1; i < menuNameList.length; i++) {
        this.menuNameHeight.push(-menuNameList[i].offsetTop);
      }
    }
  },
  methods: {
    ...mapMutations([
      "RECORD_ADDRESS",
      "RECORD_SHOPDETAIL",
      "INIT_BUYCART",
      "ADD_CART",
    ]),
    //初始化获取基本数据
    async initData() {
      if (!this.latitude) {
        //获取位置信息
        let res = await msiteAddress(this.geohash);
        //将经纬度存入vuex
        this.RECORD_ADDRESS(res);
      }
      //获取商铺信息
      this.shopDetailData = await shopDetails(
        this.shopId,
        this.latitude,
        this.longitude
      );
      //获取店铺菜单
      this.menuList = await foodMenu(this.shopId);
      //评论列表
      this.ratingList = await getRatingList(this.shopId, this.ratingOffset);
      //商铺评价分数
      this.ratingScoresData = await ratingScores(this.shopId);
      //评价tags列表
      this.ratingTagsList = await ratingTags(this.shopId);
      this.RECORD_SHOPDETAIL(this.shopDetailData);

      this.initCategoryNum();
    },
    //切换显示活动卡片
    changeShowActivities() {
      this.showActivities = !this.showActivities;
    },
    scrollListener: debounce(
      function () {
        if (this.$refs.scroll2.scroll) {
          this.scrollY = this.$refs.scroll2.scroll.y;
          let idx = this.menuNameHeight.findIndex((height, index) => {
            return (
              this.scrollY <= this.menuNameHeight[index] &&
              this.scrollY > this.menuNameHeight[index + 1]
            );
          });
          this.idx = idx > 0 ? idx : 0;
        }
      },
      100,
      { leading: true }
    ),
    menuClick(index) {
      this.$refs.scroll2.scrollTo(0, this.menuNameHeight[index]);
    },
    addToCart(category_id, item_id, food_id, name, price, specs) {
      this.ADD_CART({
        shopid: this.shopId,
        category_id,
        item_id,
        food_id,
        name,
        price,
        specs,
      });
    },
    //显示提示，无法减去商品
    showReduceTip() {
      this.showDeleteTip = true;
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        // clearTimeout(this.timer);
        this.showDeleteTip = false;
      }, 2000);
    },
    // 显示多规格商品选择卡片
    showChooseList(foods) {
      if (foods) {
        this.choosedFoods = foods;
      }
      this.showSpecs = !this.showSpecs;
      this.specsIndex = 0;
    },
    // 点击切换多规格商品index
    changeSpecsInd(index) {
      this.specsIndex = index;
    },
    /**
     * 初始化和shopCart变化时，重新获取购物车改变过的数据，赋值 categoryNum，totalPrice，cartFoodList，整个数据流是自上而下的形式，所有的购物车数据都交给vuex统一管理，包括购物车组件中自身的商品数量，使整个数据流更加清晰
     */
    initCategoryNum() {
      let newArr = [];
      let cartFoodNum = 0;
      this.totalPrice = 0;
      this.cartFoodList = [];
      this.menuList.forEach((item, index) => {
        if (this.shopCart && this.shopCart[item.foods[0].category_id]) {
          let num = 0;
          Object.keys(this.shopCart[item.foods[0].category_id]).forEach(
            (itemid) => {
              Object.keys(
                this.shopCart[item.foods[0].category_id][itemid]
              ).forEach((foodid) => {
                let foodItem = this.shopCart[item.foods[0].category_id][itemid][
                  foodid
                ];
                num += foodItem.num;
                if (item.type == 1) {
                  this.totalPrice += foodItem.num * foodItem.price;
                  if (foodItem.num > 0) {
                    this.cartFoodList[cartFoodNum] = {};
                    this.cartFoodList[cartFoodNum].category_id =
                      item.foods[0].category_id;
                    this.cartFoodList[cartFoodNum].item_id = itemid;
                    this.cartFoodList[cartFoodNum].food_id = foodid;
                    this.cartFoodList[cartFoodNum].num = foodItem.num;
                    this.cartFoodList[cartFoodNum].price = foodItem.price;
                    this.cartFoodList[cartFoodNum].name = foodItem.name;
                    this.cartFoodList[cartFoodNum].specs = foodItem.specs;
                    cartFoodNum++;
                  }
                }
              });
            }
          );
          newArr[index] = num;
        } else {
          newArr[index] = 0;
        }
      });
      this.totalPrice = this.totalPrice.toFixed(2);
      this.categoryNum = [...newArr];
    },
  },
  watch: {
    shopCart: {
      handler() {
        this.initCategoryNum();
      },
      immediate: true,
    },
  },
};
</script>
<style scoped lang='scss'>
@import '@/style/mixin';

::v-deep #head_top {
  position: relative;
  z-index: 9;

  background-color: rgba(119, 103, 137, .43);

  .iconiconfontjiantouzuo {
    color: #fff;
  }
}

.shop_container {
  position: fixed;
  top: 0;
  right: 0;
  left: 0;

  height: 100vh;

  .shop-header {
    position: relative;

    .header_cover_img_con {
      overflow: hidden;

      position: absolute;
      top: 0;
      left: 0;

      width: 100%;
      height: 100%;

      .header_cover_img {
        position: absolute;
        z-index: 8;

        width: 100%;

        filter: blur(.25rem);
      }
    }
  }
}

.description-header {
  position: relative;
  z-index: 10;

  padding: 0 .3rem;

  background-color: rgba(119, 103, 137, .43);
}

.description-top {
  display: flex;
  align-items: center;

  padding-bottom: .5rem;

  .iconarrow-left {
    color: #fff;
  }

  .description_left {
    height: 2.9rem;
    margin-right: .5rem;

    img {
      border-radius: .2rem;

@include wh(2.9rem, 2.9rem);
    }
  }
}

.description_right {
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  height: 2.9rem;

  .description-name {
    font-weight: bold;

@include sc(.8rem, #fff);
  }

  .description_text {
    margin-bottom: .3rem;

@include sc(.5rem, #fff);
  }

  .description_promotion {
    width: 11.5rem;

@include sc(.5rem, #fff);
  }
}

.detail-header-bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;

  padding: .25rem 0;

  font-size: .5rem;

  .tip-text {
    color: #fff;
  }

  .tip-icon {
    display: inline-block;

    margin-right: .2rem;
    padding: 0 .04rem;

    color: #fff;
    border-radius: .1rem;

    font-size: .4rem;
  }
}

.activities {
  position: fixed;
  z-index: 11;
  top: 0;
  left: 0;

  padding: 1.25rem;

  background-color: rgba(38, 38, 38, .9);

@include wh(100%, 100%);

  .activities-name {
    color: #fff;

    font-size: .8rem;

    text-align: center;
  }

  .activities-info,
  .shop-info {
    position: relative;
    top: 3rem;

    height: 7rem;

    .info-title {
      display: inline-block;

      padding: .2rem .5rem;

      color: #fff;
      border: .020833rem solid #fff;
      border-radius: .5rem;

      font-size: .5rem;

@include cl();
    }
  }
}

.info-content {
  position: absolute;
  top: 2rem;

  font-size: .5rem;

  .info-content-p {
    margin-bottom: .3rem;

    color: #fff;

    .info-content-span {
      display: inline-block;

      margin-right: .3rem;

      color: #fff;
      border: .025rem solid #000;
      border-radius: .1rem;
    }
  }
}

.iconquxiao1 {
  bottom: 1rem;

  color: #fff;

@include cl();
}

.change-show-type {
  display: flex;
  justify-content: space-around;

  padding: .3rem 0;

  border-bottom: .025rem solid #ebebeb;
  background-color: #fff;

  font-size: .65rem;

  span {
    display: inline-block;

    padding: .2rem;
  }

  .activate_type {
    color: #3190e8;
    border-bottom: .1rem solid #3190e8;
  }
}

.menuScrollWrapper {
  padding-bottom: 3rem;
}

.food-left {
  float: left;

  width: 20%;

  ul li {
    position: relative;

    padding: .4rem 0 .4rem .2rem;

    font-size: .6rem;

    .category_num {
      display: inline-block;

      position: absolute;
      top: .1rem;
      right: .3rem;

      min-width: .6rem;
      height: .6rem;

      color: #fff;
      border-radius: 50%;
      background-color: #ff461d;

      font-size: .5rem;
      line-height: .6rem;

      text-align: center;
    }
  }
}

.food-right {
  float: left;

  position: relative;

  width: 80%;

  .menu-name {
    font-size: .8rem;
    font-weight: bold;

    .name-des {
      margin-left: .2rem;

      font-size: .6rem;
    }
  }

  .menu-food {
    display: flex;

    margin-bottom: .1rem;

    background-color: #fff;

    .menu-food-left {
      padding: .5rem;

@include wh(2rem, 2rem);
    }

    .menu-food-mid {
      display: flex;
      flex: auto;
      flex-direction: column;
      justify-content: space-around;

      .menu-food-name {
        max-width: 5.3rem;

        font-size: .8rem;
        font-weight: bold;
      }

      .menu-food-tips {
        font-size: .5rem;
      }

      .menu-food-price {
        color: #f60;

        font-size: .6rem;
        font-weight: bold;

        .yuan {
          color: #f60;

          font-size: .4rem;
        }
      }
    }

    .menu-food-right {
      display: flex;
      align-items: center;

      padding-right: .2rem;
    }
  }
}

.actIdx {
  color: red;
  border-left: .2rem solid $blue;
}

.show_delete_tip {
  position: fixed;
  z-index: 18;
  top: 50%;
  left: 15%;

  width: 70%;
  padding: .5rem 0;

  border: 1px;
  border-radius: .25rem;
  background-color: rgba(0, 0, 0, .8);

  transform: translateY(-50%);
  text-align: center;

@include sc(.65rem, #fff);
}

.specs_cover {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;

  background-color: rgba(0, 0, 0, .4);
}

.cart-card-wrap {
  position: fixed;
  bottom: 0;

  width: 100%;
  height: 2rem;

  background-color: #fff;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.fade-enter-active,
.fade-leave-active {
  transition: all .5s ease-out;
}

</style>
